import { useEffect, useState, MutableRefObject } from 'react'
import ResizeObserver from 'resize-observer-polyfill';
window.ResizeObserver = ResizeObserver;

type ISize = {
    width: number;
    height: number;
}

/** 监听dom尺寸变化dom */
export const useDomSize = (target: MutableRefObject<any>): ISize | undefined => {
   const [size,setSize] = useState<ISize>({width:0,height:0});
   useEffect(()=>{
    const resizeObserver = new ResizeObserver((entries)=>{
       const {clientWidth,clientHeight} = entries[0].target;
       setSize({
           width: clientWidth,
           height: clientHeight
       })
    })
    resizeObserver.observe(target.current)
    return ()=>{
        resizeObserver.unobserve(target.current)
    }
   },[])
   return size;
}